import React,{useState,useReducer,useContext,useEffect,useId,useCallback} from 'react'
const UserContext=React.createContext()
const UPDATE_USERINFO_TYPE='UPDATE_USERINFO_TYPE'
const REMOVE_USERINFO_TYPE='REMOVE_USERINFO_TYPE'
const actions={
  updateUserInfo:(userinfo)=>{
    return {type:UPDATE_USERINFO_TYPE,userinfo}
  },
  logoutAction:()=>{
    return {type:REMOVE_USERINFO_TYPE}
  }
}
const reducer=(state,action)=>{
  const {type,...payloud}=action
  const {userinfo}=payloud
  switch (type) {
    case UPDATE_USERINFO_TYPE:
      return userinfo
      break;
    case REMOVE_USERINFO_TYPE:
      return {userId:'',userName:''}
      break;
    default:
      break;
  }
}
const ContentExample=()=>{
  const {state,dispatch}=useContext(UserContext)
  const {userName}=state
  useEffect(()=>{
    localStorage.setItem('userinfo',JSON.stringify(state))
  },[])
const handleQuit=useCallback(()=>{
    dispatch(actions.logoutAction())
    localStorage.removeItem('userinfo')
  },[])
  return(
    <div>
      {userName&&<p>欢迎。。。{userName}</p>}
      <button onClick={handleQuit}>退出登录</button>
    </div>
  )
}
const LoginExample=()=>{
  const id=useId()
  const {dispatch}=useContext(UserContext)
  const [userName,setUserName]=useState('')
  const [password,setPassword]=useState('')
  const ChangeFidles=useCallback((e)=>{
    const {value,name}=e.target
    if(value){
      if(name==='userName'){
        setUserName(value)
      }
      if(name==='password'){
        setPassword(value)
      }
    }
  },[userName,password])
  const handleSubmit=useCallback((e)=>{
    console.log('111')
    e.preventDefault()
    if(userName==='哈哈'&&password==='123'){
      dispatch(actions.updateUserInfo({userId:id,userName}))
    }
  },[userName,password])
  return (
    <form onSubmit={handleSubmit}>
      <p>用户名：<input value={userName} name='userName' type='text' onInput={ChangeFidles}/></p>
      <p>密码：<input value={password} name='password' type='text' onInput={ChangeFidles}/></p>
      <button>提交</button>
    </form>
  )
}
const UseReducer = (props) => {
  const [state,dispatch]=useReducer(reducer,null,()=>{
    const UserInfo=localStorage.getItem('userinfo')
    return UserInfo?JSON.stringify(UserInfo):{userId:'',userName:''}
  })
  return (
   <UserContext.Provider value={{state,dispatch}}>
     <div>
      <h1>UseReducer</h1>
      {state.userId?<ContentExample></ContentExample>:<LoginExample></LoginExample>}
    </div>
   </UserContext.Provider>
  )
}

export default UseReducer